//  订阅者
let subscription = {};

//  存量数据
let baseData = {};

const addSubscription = (type, backFun, group = '', maxSubscription = 50) => {
  if (!subscription[type]) {
    subscription[type] = {
      backList: [],
      group,
    }
  }
  if (subscription[type].backList?.length < maxSubscription) {
    subscription[type].backList.push(backFun);
  }
};

const publishMessage = (type, message = null) => {
  if (subscription[type]?.backList?.length) {
    subscription[type].backList.forEach(backFun => {
      backFun(message)
    })
  }
};

const removeSubscription = type => {
  delete subscription[type]
};

const removeSubscriptionByGroup = (group, exception = []) => {
  Object.keys(subscription).forEach(key => {
    if (subscription[key].group === group && !exception.some(type => type === key)) {
      delete subscription[key]
    }
  })
};

const addBaseData = (type, data) => {
  baseData[type] = data;
};

const removeBaseData = type => {
  delete baseData[type]
};

const getBaseData = type => {
  return baseData[type]
};

export {
  addSubscription,
  publishMessage,
  addBaseData,
  removeBaseData,
  getBaseData,
  removeSubscription,
  removeSubscriptionByGroup
}
